package org.openbiz.appbiz.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.openbiz.appbiz.service.GenericManager;
import org.openbiz.appbiz.model.Who;
import org.openbiz.appbiz.webapp.action.BaseAction;

import java.util.List;

public class WhoAction extends BaseAction implements Preparable {
    private GenericManager<Who, Long> whoManager;
    private List whoes;
    private Who who;
    private Long  did;

    public void setWhoManager(GenericManager<Who, Long> whoManager) {
        this.whoManager = whoManager;
    }

    public List getWhoes() {
        return whoes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String whoId = getRequest().getParameter("who.did");
            if (whoId != null && !whoId.equals("")) {
                who = whoManager.get(new Long(whoId));
            }
        }
    }

    public String list() {
        whoes = whoManager.getAll();
        return SUCCESS;
    }

    public void setDid(Long  did) {
        this. did =  did;
    }

    public Who getWho() {
        return who;
    }

    public void setWho(Who who) {
        this.who = who;
    }

    public String delete() {
        whoManager.remove(who.getDid());
        saveMessage(getText("who.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (did != null) {
            who = whoManager.get(did);
        } else {
            who = new Who();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (who.getDid() == null);

        whoManager.save(who);

        String key = (isNew) ? "who.added" : "who.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}